package org.xiaoyu.rpc.loadbalance;

import org.xiaoyu.rpc.Loadbalancer;
import org.xiaoyu.rpc.common.url.URL;
import org.xiaoyu.rpc.remoting.packet.Invocation;

import java.util.List;
import java.util.Random;

/**
 * Created By Have
 * 2021/7/14 15:37
 */
public class RandomLoadbalancer implements Loadbalancer {
    private ThreadLocal<Random> threadLocalRandom = ThreadLocal.withInitial(() -> {
        Random random = new Random();
        return random;
    });

    @Override
    public URL loadBalance(List<URL> urls, Invocation invocation) {
        Random random = threadLocalRandom.get();
        int index = random.nextInt(urls.size());
        threadLocalRandom.remove();
        return urls.get(index);
    }
}
